const pool = require('../config/db');
const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

const User = {
    async create({ email, phone, full_name, username, password }) {
        const user_id = uuidv4();
        const password_hash = await bcrypt.hash(password, 10);

        const connection = await pool.getConnection();
        try {
            await connection.beginTransaction();

            await connection.query(
                'INSERT INTO users (user_id, email, phone, full_name, username, password_hash) VALUES (?, ?, ?, ?, ?, ?)',
                [user_id, email, phone, full_name, username, password_hash]
            );

            await connection.query('INSERT INTO user_stats (user_id) VALUES (?)', [user_id]);

            await connection.commit();
            return { user_id };
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    },

    async findByEmail(email) {
        const [rows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
        return rows[0];
    },

    async findById(user_id) {
        const [rows] = await pool.query(
            'SELECT u.*, us.posts_count, us.followers_count, us.following_count FROM users u LEFT JOIN user_stats us ON u.user_id = us.user_id WHERE u.user_id = ?',
            [user_id]
        );
        return rows[0];
    },

    async update(user_id, updates) {
        const { email, phone, full_name, username, bio, avatar_url } = updates;
        await pool.query(
            'UPDATE users SET email = ?, phone = ?, full_name = ?, username = ?, bio = ?, avatar_url = ? WHERE user_id = ?',
            [email, phone, full_name, username, bio, avatar_url, user_id]
        );
    }
};

module.exports = User;